package com.example.photongrid;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URL;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Enumeration;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import android.net.wifi.p2p.WifiP2pManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.support.v4.app.NavUtils;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Build;

public class HostGameActivity extends Activity {
	

	private String string = new String();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_host_game);
		
		new HostGameTask().execute();
		
		Server server = new Server();
		Thread serverThread = new Thread(server);
		serverThread.start();
		
		final Button refreshButton = (Button) findViewById(R.id.refreshButton);
	    refreshButton.setOnClickListener(new View.OnClickListener() {
	      public void onClick(View view) {
	    	  //try {
				//getCurrentIP();
	    		  TextView tv = (TextView) findViewById(R.id.ServerIP);
					tv.setText(getLocalIpAddress());
			/*} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				TextView tv = (TextView) findViewById(R.id.ServerIP);
				tv.setText("M Error");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				TextView tv = (TextView) findViewById(R.id.ServerIP);
				tv.setText("IO Error");
			}*/
	    }
	    });
	    
	    final Button startGameButton = (Button) findViewById(R.id.startGameButton);
	    startGameButton.setOnClickListener(new View.OnClickListener() {
	      public void onClick(View view) {
	    	  Intent myIntent = new Intent(getApplicationContext(), HarnessServer.class);
			  startActivity(myIntent);
	    }
	    });
	    
	    
	    
		// Show the Up button in the action bar.
		
		setupActionBar();
	}
	
	@Override
	protected void onStop()
	{
		super.onStop();
		//new RemoveGameTask().execute();
	}
	
	
	/**
	 * Set up the {@link android.app.ActionBar}, if the API is available.
	 */
	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	private void setupActionBar() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
			getActionBar().setDisplayHomeAsUpEnabled(true);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.host_game, menu);
		
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			// This ID represents the Home or Up button. In the case of this
			// activity, the Up button is shown. Use NavUtils to allow users
			// to navigate up one level in the application structure. For
			// more details, see the Navigation pattern on Android Design:
			//
			// http://developer.android.com/design/patterns/navigation.html#up-vs-back
			//
			NavUtils.navigateUpFromSameTask(this);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	public void getCurrentIP () throws  MalformedURLException, IOException {
	    
		TextView ip;
		
		ip = (TextView) findViewById(R.id.ServerIP);
		ip.setText("Please wait...");  
		
		
		new GetUrlTask().execute();
	    	
		ip.setText(string);
	    	      
	}
	
	// gets the ip address of your phone's network
    private String getLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                    	Log.i("Server IP", inetAddress.getHostAddress().toString());
                    	return inetAddress.getHostAddress().toString(); }
                }
            }
        } catch (SocketException ex) {
            Log.e("ServerActivity", ex.toString());
        }
        return null;
    }

	private class GetUrlTask extends AsyncTask<Void, String, String> {
	    protected void onPostExecute(String result) {
	    }

		@Override
		protected String doInBackground(Void... params) {
			// TODO Auto-generated method stub
			try {
				String str;
				HttpClient httpclient = new DefaultHttpClient();
	            //HttpGet httpget = new HttpGet("http://www.whatismyip.com/?404");
	            //HttpGet httpget = new HttpGet("http://whatismyip.com.au/");
	            HttpGet httpget = new HttpGet("http://ip2country.sourceforge.net/ip2c.php?format=JSON");
	            HttpResponse response;

	            response = httpclient.execute(httpget);

	            //Log.i("externalip",response.getStatusLine().toString());

	            HttpEntity entity = response.getEntity();
	            entity.getContentLength();
	            str = EntityUtils.toString(entity);
	            try {
	             JSONObject obj =  (new JSONObject(str));
	                str = obj.getString("ip");
	              
	            } catch (JSONException e) {
	              e.printStackTrace();
	            }
	              string = str;
			      Log.i("IP", string);
			    

		    } catch (MalformedURLException e) {

		        e.printStackTrace();
		    } catch (IOException e) {

		        e.printStackTrace();
		    }
			return null;
		}
	}
		
		
		private class HostGameTask extends AsyncTask<Void, String, String> {
		    protected void onPostExecute(String result) {
		    }

			@Override
			protected String doInBackground(Void... params) {
				// TODO Auto-generated method stub
				try {
					String str;
					HttpClient httpclient = new DefaultHttpClient();
		            HttpGet httpget = new HttpGet("http://ip2country.sourceforge.net/ip2c.php?format=JSON");
		            HttpResponse response;
		            response = httpclient.execute(httpget);
		            HttpEntity entity = response.getEntity();
		            entity.getContentLength();
		            str = EntityUtils.toString(entity);
		            try {
		            	JSONObject obj =  (new JSONObject(str));
		                str = obj.getString("ip");
		            } 
		            catch (JSONException e) {
		            	e.printStackTrace();
		            }
		            string = str;
				    Log.i("IP", string);
				    
				    //tell DB that I am creating a game and get an assigned ID number
					try 
					{
							DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
							Connection conn = DriverManager.getConnection("jdbc:oracle:thin:hr/hr@oracle1.cise.ufl.edu:1521:orcl", "s93022ai", "adt2913*");  // don't go hacking my account Nuri :P lol
							Statement stmt = conn.createStatement();
							String query = "insert into HOSTEDGAMES (HOSTIP, NUMPLAYERS, MAXPLAYERS, PLAYER0) values ('" + string + "', 1, 2, 'testPlayer1')";
							stmt.executeQuery(query);
							conn.close();				
					} 
					catch (SQLException e) 
					{
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				    
				} 
				catch (MalformedURLException e) {
					e.printStackTrace();
				}
			    catch (IOException e) {
			        e.printStackTrace();
			    }
				return null;
			}

		
	}

		
		private class RemoveGameTask extends AsyncTask<Void, String, String> {
		    protected void onPostExecute(String result) {
		    }

			@Override
			protected String doInBackground(Void... params) {
				// TODO Auto-generated method stub
				try 
				{
						Log.i("String is", string);
						DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
						Connection conn = DriverManager.getConnection("jdbc:oracle:thin:hr/hr@oracle1.cise.ufl.edu:1521:orcl", "s93022ai", "adt2913*");  // don't go hacking my account Nuri :P lol
						Statement stmt = conn.createStatement();
						String query = "DELETE FROM HOSTEDGAMES WHERE HOSTIP = '" + string + "'";
						stmt.executeQuery(query);
						conn.close();			
						
				} 
				catch (SQLException e) 
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return null;
			}

		
	}

}


